<template>
  <section class="app-main">
    <div class="app-container">
      <div class="el-row">
        <!-- 左侧树形结构 -->
        <div class="el-col el-col-4 el-col-xs-24">
          <!-- <div class="head-container">
            <el-input
              v-model="treeFilterText"
              placeholder="请输入分类名称"
              prefix-icon="el-icon-search"
              size="small"
              style="margin-bottom: 20px;"
            />
          </div> -->

          <div class="head-container">
            <el-tree
              ref="tree"
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="el-col el-col-20 el-col-xs-24">
          <!-- 搜索表单 -->
          <el-form :inline="true" :model="queryParams" size="small">
            <el-form-item label="产品物料编码">
              <el-input v-model="queryParams.item_code" placeholder="请输入产品物料编码" />
            </el-form-item>
            <el-form-item label="产品物料名称">
              <el-input v-model="queryParams.item_name" placeholder="请输入产品物料名称" />
            </el-form-item>
            <el-form-item label="批次号">
              <el-input v-model="queryParams.batch_code" placeholder="请输入批次号" />
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-input v-model="queryParams.warehouse_name" placeholder="请输入仓库名称" />
            </el-form-item>
            <el-form-item label="库区名称">
              <el-input v-model="queryParams.location_name" placeholder="请输入库区名称" />
            </el-form-item>
            <el-form-item label="库位编码">
              <el-input v-model="queryParams.area_code" placeholder="请输入库位编码" />
            </el-form-item>
            <el-form-item label="是否冻结">
              <el-select v-model="queryParams.frozen_flag" placeholder="请选择">
                <el-option label="是" value="Y" />
                <el-option label="否" value="N" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 操作按钮 -->
          <div class="mb8 el-row">
            <div class="el-col el-col-1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" plain>导出</el-button>
            </div>
            <div class="top-right-btn">
              <el-button icon="el-icon-search" circle size="mini" />
              <el-button icon="el-icon-refresh" circle size="mini" @click="getList" />
            </div>
          </div>

          <!-- 表格 -->
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%;font-size: 12px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" min-width="55" align="center" />
            <el-table-column label="产品物料编码" prop="item_code" min-width="120" align="center" />
            <el-table-column label="产品物料名称" prop="item_name" min-width="150" align="center" show-overflow-tooltip />
            <el-table-column label="规格型号" prop="stock_sfn" min-width="80" align="center" show-overflow-tooltip />
            <el-table-column label="在库数量" prop="quantity_num" min-width="80" align="center" />
            <el-table-column label="单位" prop="unit_name" min-width="80" align="center" />
            <el-table-column label="批次号" prop="batch_code" min-width="150" align="center" show-overflow-tooltip />
            <el-table-column label="仓库" prop="warehouse_name" min-width="80" align="center" />
            <el-table-column label="库区" prop="location_name" min-width="80" align="center" />
            <el-table-column label="库位" prop="area_name" min-width="80" align="center" />
            <el-table-column label="入库日期" prop="create_time" min-width="120" align="center">
              <template slot-scope="scope">
                {{ formatDate(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column label="是否冻结" prop="frozen_flag" min-width="100" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.frozen_flag"
                  active-value="Y"
                  inactive-value="N"
                  @change="handleFrozenChange(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
  </section>
</template>

<script>

import {listType, listInventory, updateInventoryFrozen} from "@/views/ck/js/inventory";

export default {
  name: 'InventoryManagement',
  data() {
    return {
      // 树形搜索
      treeFilterText: '',
      // 树形数据
      treeData: [
      ],
      defaultProps: {
        children: 'basicWlflz',
        label: (data, node) => {
          // 最终制品节点
          if (data.label) {
            return data.label
          }
          // 一级节点
          if (data.material_classification_name) {
            return data.material_classification_name
          }
          // 二级节点
          if (data.material_subcategory_name) {
            return data.material_subcategory_name
          }
          return ''
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        item_code: undefined,
        item_name: undefined,
        batch_code: undefined,
        warehouse_name: undefined,
        location_name: undefined,
        area_code: undefined,
        frozen_flag: undefined,
        material_classification_id: undefined,
        material_subcategory_id: undefined
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 总条数
      total: 0,
      // 选中数组
      ids: [],

    }
  },
  watch: {
    treeFilterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getInventory()
    this.getType()
  },
  methods: {
    // 筛选树形节点
    filterNode(value, data) {
      if (!value) return true
      return (data.label && data.label.indexOf(value) !== -1)
        || (data.material_classification_name && data.material_classification_name.indexOf(value) !== -1)
        || (data.material_subcategory_name && data.material_subcategory_name.indexOf(value) !== -1)
    },
    // 树形节点点击
    handleNodeClick(data) {
      console.log("测试点击父分类："+data.material_classification_id);
      console.log("测试点击子分类："+data.material_subcategory_id);
      this.queryParams.material_classification_id = data.material_classification_id;
      this.queryParams.material_subcategory_id = data.material_subcategory_id
      this.getInventory() //重新查询
    },
    // 获取库存列表数据
    getInventory() {
      this.loading = true
      listInventory(this.queryParams).then(resp => {
        console.log("测试获取数据:"+resp.rows);
        this.tableData = resp.rows
        this.total = resp.total
        this.loading = false
      })
    },
    // 获取数据列表
    getList() {
      this.getInventory()
    },
    //获取分类数据
    getType() {
      this.loading = true
      listType().then(resp => {
        // 增加最大父级"最终制品"
        this.treeData = [{
          id: 0,
          label: '最终制品',
          basicWlflz: resp // children字段要和defaultProps一致
        }]
        this.loading = false
      })
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getInventory()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        item_code: undefined,
        item_name: undefined,
        batch_code: undefined,
        warehouse_name: undefined,
        location_name: undefined,
        area_code: undefined,
        frozen_flag: undefined
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    // 冻结状态改变
    handleFrozenChange(row) {
      // 构建确认消息
      const actionText = row.frozen_flag === 'Y' ? '冻结' : '解冻';
      const confirmMessage = `确认要${actionText}物料 "${row.item_name}" 吗？`;
      
      this.$confirm(confirmMessage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载状态
        const loading = this.$loading({
          lock: true,
          text: `正在${actionText}物料，请稍候...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 调用API更新冻结状态
        updateInventoryFrozen(row.item_id, row.frozen_flag).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success(`${actionText}操作成功！`);
            this.getInventory(); // 刷新列表
          } else {
            this.$message.error(response.msg || `${actionText}操作失败`);
            row.frozen_flag = row.frozen_flag === 'Y' ? 'N' : 'Y'; // 恢复开关状态
          }
        }).catch(error => {
          loading.close();
          console.error('冻结状态更新失败:', error);
          this.$message.error(`${actionText}操作失败`);
          row.frozen_flag = row.frozen_flag === 'Y' ? 'N' : 'Y'; // 恢复开关状态
        });
      }).catch(() => {
        // 取消操作，恢复开关状态
        row.frozen_flag = row.frozen_flag === 'Y' ? 'N' : 'Y';
      });
    },
    // 日期格式化
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
}
</script>

<style scoped>
.app-main {
  padding: 10px;
}
.app-container {
  padding: 5px;
}
.head-container {
  margin-bottom: 5px;
}
.mb8 {
  margin-bottom: 5px;
}
.top-right-btn {
  float: right;
}
.el-col-4{
  padding-right: 50px;
}
</style>
